package com.sqx.modules.app.utils;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.alibaba.fastjson.JSONObject;
import com.sqx.common.utils.Result;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import
        org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;


@Slf4j
public class CustomerSmsUtils {

    private static final String URL ="https://enjoymov.co/prod-api/kstbCore/sms/send";

    public static Result send(String phone, int code) {
        String merchantId = "KSTB961025";
        String md5_key = "314F3C7B9DE29AAA85024921AF8A8658";
        Map<String, Object> param = new HashMap<>();
        param.put("content", "【七旺影视】 验证码为"+code+"，请勿与他人分享。");
        param.put("phone", "86"+phone);
        param.put("type", 2);//1.marketing message 2.OTP message
        param.put("msgChannel", "38");
        param.put("merchantId", merchantId);
        param.put("countryCode", "86");
//        param.put("sid", "AKULAKU");
//        param.put("callbackUrl", "172.18.10.118:8182/sqx_fast/callbackTest");
//param.put("templateId", "31");
        param.put("sign", generateSign(param, md5_key));
        String smsjson = JSONObject.toJSONString(param);
        log.info("发送短信 :{}", smsjson);
        try {
//发送
            RestTemplate restTemplate = createTemplate();
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add("Content-Type", "application/json");
            HttpEntity<Map<String, Object>> requestEntity = new
                    HttpEntity<>(param, requestHeaders);
            String result = restTemplate.postForObject(URL, requestEntity,
                    String.class);
            KstbSmsResponse res = JSONObject.parseObject(result,
                    KstbSmsResponse.class);
            if (res.getCode()==200){
                log.info("短信发送结果 :{}", res.toString());
                return Result.success("短信发送成功");
            }else {
                return Result.error("短信发送失败");
            }


        } catch (Exception e) {
// process exception
        }
        return Result.error("短信发送失败");
    }


    private static RestTemplate createTemplate() throws
            NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain,
                                                String authType) -> true;
        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy)
                .build();
        SSLConnectionSocketFactory csf = new
                SSLConnectionSocketFactory(sslContext);
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(csf)
                .build();
        HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        return restTemplate;
    }


    public static String generateSign(Map<String, Object> param, String
            md5_key) {
        StringBuffer sb = new StringBuffer();
        sb.append(md5_key).append(param.get("merchantId")).append(param.get("phone")
        ).append(param.get("content"));
        String sign = new
                Digester(DigestAlgorithm.MD5).digestHex(sb.toString());
        return sign;
    }


    @Data
    private static class KstbSmsResponse {
        private Integer code;
        private String message;private Boolean data;
    }


}
